/*
 * Niiuzu
 * Copyright (C) 2011  Thierry Nowak
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.niiuzu.server.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Classe utilitaire comprenant les fonctions de hachage utilisée dans
 * l'application.
 * 
 * @see <a
 *      href="http://en.wikipedia.org/wiki/Hash_function">http://en.wikipedia.org/wiki/Hash_function</a>
 */
public final class HashUtil {

	private static final String HASH_ALGORITHM_SHA1 = "SHA-1";

	private static final String CHARSET_NAME_UTF8 = "UTF-8";

	/**
	 * Construit une nouvelle instance de {@link HashUtil}.
	 */
	private HashUtil() {
	}

	/**
	 * Retourne le résultat de l'encodage SHA-1 d'une chaîne de caractères.
	 */
	public static String hashSha1(String value) {
		String hashCode = null;

		if (value == null) {
			return null;
		}

		try {
			byte[] bytesValue = value.getBytes(CHARSET_NAME_UTF8);

			MessageDigest messageDigest;
			messageDigest = MessageDigest.getInstance(HASH_ALGORITHM_SHA1);

			messageDigest.update(bytesValue);
			byte[] digest = messageDigest.digest();

			hashCode = BytesUtil.convertBytesToString(digest);

		} catch (UnsupportedEncodingException e) {
			throw new IllegalArgumentException(e);
		} catch (NoSuchAlgorithmException e) {
			throw new IllegalArgumentException(e);
		}

		return hashCode;
	}
}
